import json

from flask import Flask, session, redirect, url_for, escape, request, jsonify
from .mssql import  mssql
from .dataKV import dataKV
from .svrData import svrData
from .comm import comm
from . import  config

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
app.debug = False
@app.route("/")
def route_root():
    return 'web server root.'
@app.route("/<module>/<category>/<action>" , methods=['POST','GET'])
def db_ms_reload(module , category , action):
    #print(module , category , action)
    router = "/"+ module+ "/"+ category+ "/"+ action
    return callApi(router)
# @app.route("/db/ms/reload")
# def db_ms_reload():
#     return callApi("/db/ms/reload")
# @app.route("/db/ms/query" , methods=['POST','GET'])
# def db_ms_query():
#     return callApi("/db/ms/query")



routerHandlers ={
    "/db/ms/reload" : mssql.mssqlClient.reload ,
    "/db/ms/query" : mssql.mssqlClient.webQuery ,
    "/data/io/kv" : dataKV.dataKv.webAction ,
    "/zn/svr/postData" : svrData.svrData.apiPost,
    "/zn/svr/getFullVars" : svrData.svrData.apiGetFullVars,
    "/zn/svr/getDevVars" : svrData.svrData.apiGetDevVars,
    "/zn/svr/getDict" : svrData.svrData.apiGetDict,
    "/zn/svr/getHisDp" : svrData.svrData.apiHisDp,
    "/comm/tdb/query" : comm.comm.webQuery,
    "/comm/tdb/postBatch" : comm.comm.webPostBatchDatapoints ,
}
def init():
    try:
        configPath = config.sysConfig['dbms']['configPath']
        print('load ms config by path:', configPath)
        mssql.mssqlClient.loadConnerctions(configPath)
        svrData.svrData.dbConnection =  mssql.mssqlClient.connections['znv2']
        svrData.svrData.load()


        tdbKey = "psc2024"
        tdbHost = "hh.hhdata.cn"
        tdbPort= 31299
        tdbToken= "Basic cm9vdDpoaHVjMTExNQ=="
        tdbDB= "pcs2024"
        tdbSqlRootPath="./libs/comm/tdbSqls"
        comm.comm.registDB(tdbKey , tdbHost, tdbPort , tdbDB , tdbToken , tdbSqlRootPath)
        tdbKey = "iotv10"
        comm.comm.registDB(tdbKey , tdbHost, tdbPort , tdbDB , tdbToken , tdbSqlRootPath)
    except Exception as er:
        print(er)
def callApi(apiKey):
    res ={
        "version":"pywebsvr-2024",
        "apiKey": apiKey,
        "result": None,
        "error": {
            "code":0 ,
            "message":""
        }
    }
    try:
        params ={}
        for k,v in request.values.items():
             params[k] = v
        if len(request.data)>0:
            ps = json.loads(request.data)
            for k ,v in ps.items():
                params[k] = v
        if apiKey in routerHandlers.keys():
            try:
                fun = routerHandlers[apiKey]
                fun(res , params , request)
            except Exception as haEr:
                print(haEr)
        else:
            res['error']['code']= -1
            res['error']['message'] = 'apiKey is error'
    except Exception as eer:
        print(eer)
    return  jsonify(res)
def startWebapiSvc(localPort = 31298):
    try:
        print('00000000000000000000000000000000000000000000000000000000000000000000')
        app.run(host='0.0.0.0',debug=True, port=localPort)
    except Exception as er:
        print(er)

init()